package org.kolonitsky.translator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.MissingResourceException;

/**
 * @author Alex.Kolonitsky
 */
public abstract class Translators<T extends Translator> extends HashMap<Lang, T> {

    protected static final Log LOG = LogFactory.getLog(Translators.class);

    public Translator get(Lang lang) {
        assert lang == null || lang.equals(Lang.DEFAULT);

        T res = super.get(lang);
        if (res == null) {
            res = newTranslator(lang);
            this.put(lang, res);
        }

        return res;
    }

    public String translate(Lang lang, String key) {
        try {
            return this.get(lang).translate(key);
        } catch (MissingResourceException e) {
            LOG.warn("Translation for '" + key + "' not found");
        }
        return null;
    }

    protected abstract T newTranslator(Lang lang);
}
